<template>
  <!-- 通知配置 -->
  <div class="notice-config">
    <el-form :model="form" :label-width="labelWidth + 'px'" ref="formRef">
      <el-form-item>
        <template #label v-if="showTitle">
          <span class="label">通知配置</span>
          <el-popover title="" :width="200" trigger="hover" effect="light" content="通知场景包含商品库存预警通知、商品下架通知"
            placement="bottom">
            <template #reference>
              <span class="tips-icon">!</span>
            </template>
          </el-popover>
        </template>
        <el-checkbox class="common-check" v-model="check1" label="系统通知"></el-checkbox>
        <el-form-item prop="noticeUserIds" :rules="[{ required: check1, message: '请选择', trigger: 'blur' }]">
          <el-select v-model="form.noticeUserIds" placeholder="请选择" clearable multiple>
            <el-option v-for="item in realationList" :label="item.realName" :key="item.id" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-form-item>
          <el-checkbox class="common-check" v-model="check2" label="企微群通知"></el-checkbox>
          <el-form-item prop="wechatUrl" :rules="formRules.url">
            <el-input v-model="form.wechatUrl" placeholder="请输入通知链接" clearable></el-input> </el-form-item>
        </el-form-item>
        <span class="special-divider">@</span>
        <el-form-item prop="wechatTel" :rules="formRules.tel">
          <el-input v-model="form.wechatTel" maxlength="11" placeholder="请输入企微员工手机号" clearable></el-input>
        </el-form-item>
      </el-form-item>
      <el-form-item>
        <el-button link type="primary" @click="showPreviewr = true">查看配置示例图</el-button>
      </el-form-item>
      <el-form-item v-show="showError">
        <span class="error">请选择通知配置</span>
      </el-form-item>
    </el-form>

    <div v-if="showPreviewr">
      <el-image-viewer hide-on-click-modal @close="showPreviewr = false"
        :url-list="['https://minio.lianhaikeji.com/marketing/marketing-center/1692087273000aE8iNPR5.png']"></el-image-viewer>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { phone_complicated, httpUrl } from "@/utils/commonRegexp";
import { getSystemNoticeUser } from "@/api/activity"
import { getSysNoticeUser } from '@/api/pointsMall'
import { queryMemberMerchantInfos } from "@/api/vipCenter";
const props = defineProps({
  showTitle: {
    type: Boolean,
    default: true
  },
  labelWidth: {
    type: Number,
    default: 120
  },
  serviceType: {
    type: String,
    default: ''
  },
  actId: {
    type: [String, Number],
    default: ''
  },
  mallId: {
    type: [String, Number],
    default: ''
  },
  memberId:{
    type: [String, Number],
    default: ''
  }
})
const realationList = ref<{ realName: string, id: string | number }[]>([])
const showPreviewr = ref(false)
const check1 = ref(false)
const check2 = ref(false)
const showError = ref(false)
const formRef = ref()

const formRules = {
  tel: [{
    trigger: 'blur',
    validator(rule, value, callback) {
      if (check2.value) {
        if (value) {
          if (!phone_complicated.test(value)) {
            callback('手机号格式不正确！')
          } else {
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
  }],
  url: [{
    trigger: 'blur',
    validator(rule, value, callback) {
      if (check2.value) {
        if (value) {
          if (httpUrl.test(value)) {
            callback()
          } else {
            callback('链接格式不正确！')
          }
        } else {
          callback('请输入链接！')
        }
      } else {
        callback()
      }
    }
  }]
}
const form = reactive({
  noticeUserIds: [],
  wechatUrl: '',
  wechatTel: ''
})

const getSysUser = async (api: any, id: string | number) => {
  const res = await api({ id })
  if (res.code == 200) {
    return res
  }
}

watch(() => [props.serviceType,props.actId,props.mallId,props.memberId], async (val) => {
  let data
  if(val[0]=='mall'){
    if(val[2]){
      data = await getSysUser(getSysNoticeUser, props.mallId)
    }
  } else if (val[0] == 'activity') {
    if(val[1]){
      data = await getSysUser(getSystemNoticeUser, props.actId)
    }
  }else if(val[0] == 'member'){
    if(val[3]){
      data = await getSysUser(queryMemberMerchantInfos, props.memberId)
    }
  }
  if (data?.code == 200) {
    realationList.value = data.payload ?? []
  }
}, { immediate: true })


const validForm = () => {
  return new Promise((resolve, reject) => {
    if (!check1.value && !check2.value) {
      showError.value = true
      // ElMessage.error('请选择通知配置')
      reject()
      return
    }
    showError.value=false
    formRef.value.validate((valid:boolean)=>{
      if(valid){
        let noticeType=0
        if(check1.value&&check2.value){
          noticeType=2
        }else{
          noticeType=check1.value?0:1
        }
        const data={
          noticeType:noticeType,
          noticeWebhookUrls:form.wechatUrl,
          noticePhones:form.wechatTel,
          noticeUserIds:form.noticeUserIds
        }
        resolve(data)
      } else {
        reject()
      }
    })
  })
}

const resetForm = () => {
  check1.value = false
  check2.value = false
  showPreviewr.value = false
  showError.value = false
  formRef.value.resetFields()
}
//填充表单信息
const getFormData = (data: { noticeType: 0 | 1, noticeWebhookUrls?: string, noticePhones?: string, noticeUserIds?: string }) => {
  resetForm()
  if(data.noticeType==0){
    check1.value=true
    form.noticeUserIds=(data.noticeUserIds?data.noticeUserIds.split(','):[]).map(Number)
  }else if(data.noticeType==1){
    check2.value=true
    form.wechatTel=data.noticePhones??''
    form.wechatUrl=data.noticeWebhookUrls??''
  }else if(data.noticeType==2){
    check2.value=true
    check1.value=true
    form.noticeUserIds=(data.noticeUserIds?data.noticeUserIds.split(','):[]).map(Number)
    form.wechatTel=data.noticePhones??''
    form.wechatUrl=data.noticeWebhookUrls??''
  }
}
defineExpose({
  resetForm,
  validForm,
  getFormData
})

</script>
<style lang="scss" scoped>
.common-check {
  width: 120px;
}

.label:before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

.special-divider {
  color: #666;
  margin: 8px;
}

.error {
  color: var(--el-color-danger);
  font-size: 12px;
}

.tips-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  margin-left: 4px;
  margin-top: 8px;
  font-size: 10px;
  color: var(--el-text-color-regular);
  border-radius: 50%;
  border: 1px solid var(--el-text-color-regular);
}
</style>